# -*- coding: utf-8 -*-
from dwjjCoreClientScripts.common import consts, logger

import mod.client.extraClientApi as clientAPI
from mod.client.system.clientSystem import ClientSystem


class WorldModule(object):
    worldProtectDict = dict()

    def __init__(self, clientSystem):
        # type: (ClientSystem) -> None
        self.clientSystem = clientSystem
        self.Init()
        self.InitComp()
        self.SetListener()

    def Init(self):
        self.localPlayerId = clientAPI.GetLocalPlayerId()

    def InitComp(self):
        self.gameComp = clientAPI.GetEngineCompFactory().CreateGame(clientAPI.GetLevelId())
        self.blockUseEventWhiteList = clientAPI.GetEngineCompFactory().CreateBlockUseEventWhiteList(clientAPI.GetLevelId())

    def SetListener(self):
        # 客户端加载事件
        self.clientSystem.ListenForEvent(clientAPI.GetEngineNamespace(), clientAPI.GetEngineSystemName(), "OnLocalPlayerStopLoading", self, self.OnLocalPlayerStopLoading, 0)
        # 来自服务端的回复
        self.clientSystem.ListenForEvent(consts.ServerModName, consts.ServerSystemName, consts.WorldModuleConfigResponse, self, self.OnConfigResponse, 0)
        # 世界保护模块
        self.clientSystem.ListenForEvent(clientAPI.GetEngineNamespace(), clientAPI.GetEngineSystemName(), "PlayerTryDestroyBlockClientEvent", self, self.OnPlayerTryDestroyBlock, 0)
        self.clientSystem.ListenForEvent(clientAPI.GetEngineNamespace(), clientAPI.GetEngineSystemName(), "ClientBlockUseEvent", self, self.OnBlockUse, 0)

    # 客户端加载事件 触发配置获取请求
    def OnLocalPlayerStopLoading(self, e):
        if e['playerId'] != self.localPlayerId:
            return
        self.clientSystem.NotifyToServer(consts.WorldModuleConfigRequest, {'playerId': self.localPlayerId})

    # 来自服务端的回复
    def OnConfigResponse(self, e):
        # 世界保护模块
        self.worldProtectDict = e["worldProtect"]
        for k in self.worldProtectDict["useProtect"]:
            for v in self.worldProtectDict["useProtect"][k]:
                self.blockUseEventWhiteList.AddBlockItemListenForUseEvent(v + ":*")

    # ------ 世界保护部分 ------

    def OnPlayerTryDestroyBlock(self, e):
        if self.gameComp.GetCurrentDimension in self.worldProtectDict["breakProtect"]:
            e["cancel"] = True

    def OnBlockUse(self, e):
        dim = str(self.gameComp.GetCurrentDimension())
        if dim in self.worldProtectDict["useProtect"]:
            blockName = e["blockName"]
            if blockName in self.worldProtectDict["useProtect"][dim]:
                e["cancel"] = True
